package com.provider.test.netty;

import com.alibaba.fastjson.JSONObject;
import com.common.test.entity.RpcRequest;
import com.provider.test.service.UserServiceImpl;
import com.provider.test.utils.SpringContextHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


public class UserServerHandler extends ChannelInboundHandlerAdapter {




    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {


        RpcRequest rpcRequest= (RpcRequest) msg;

         String className = rpcRequest.getClassName();
         String methodName = rpcRequest.getMethodName();
         String className1 =rpcRequest.getClassName();
         Object[] parameters = rpcRequest.getParameters();

         Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        Object userService = SpringContextHolder.getBean("userService");
      if (null!=userService){
           Class<?> aClass = userService.getClass();

           Method declaredMethod = aClass.getDeclaredMethod(methodName,parameterTypes);
           Object invoke = declaredMethod.invoke(userService, parameters);
           rpcRequest.setResult((String) invoke);
           ctx.writeAndFlush(rpcRequest);
      }

    }


}
